package com.xuecheng.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.auth.mapper.XcUserMapper;
import com.xuecheng.auth.model.dto.RegisterRequestDto;
import com.xuecheng.auth.model.po.XcUser;
import com.xuecheng.auth.model.po.XcUserRole;
import com.xuecheng.auth.service.XcUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@Service
public class XcUserServiceImpl extends ServiceImpl<XcUserMapper, XcUser>
        implements XcUserService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    PasswordEncoder passwordEncoder;

    /**
     * 开通账号
     * @param companyId
     * @return
     */
    @Override
    public XcUser createAccount(Long companyId) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        XcUser user = new XcUser();
        user.setUsername(generateAccount());
        //设置初始密码为123456
        user.setPassword(encoder.encode("123456"));
        user.setCompanyId(companyId);
        user.setStatus("1");
        save(user);
        return user;
    }

    /**
     * 生成账号，前6位是当天日期yyMMdd，后6位是该账户在当天创建的序号，第一个就是000000
     * @return
     */
    private String generateAccount(){
        String yyMMdd = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMdd"));
        String key = "account:seq:" + yyMMdd;
        Long increment = stringRedisTemplate.opsForValue().increment(key) - 1;
        String num = String.format("%06d",increment);
        return yyMMdd + num;
    }

    /**
     * 学生注册账号
     * @param request
     * @return
     */
    @Transactional
    @Override
    public XcUser register(RegisterRequestDto request) {
        //首先验证验证码
        String key = request.getCheckcodekey();
        String rightCode = stringRedisTemplate.opsForValue().get(key);
        if(rightCode == null){
            throw new RuntimeException("验证码已过期");
        }
        String code = request.getCheckcode();
        if(!rightCode.equalsIgnoreCase(code)){
            throw new RuntimeException("验证码不正确");
        }
        //然后判断两次密码是否一致
        String password = request.getPassword();
        String confirmpwd = request.getConfirmpwd();
        if(!password.equals(confirmpwd)){
            throw new RuntimeException("两次密码输入不一致");
        }
        //然后判断当前账号是否存在
        int usernameExist = count(new LambdaQueryWrapper<XcUser>()
                .eq(XcUser::getUsername, request.getUsername()));
        if(usernameExist > 0){
            throw new RuntimeException("当前账号已存在");
        }
        //然后判断电话和邮箱是否存在
        int phoneExist = count(new LambdaQueryWrapper<XcUser>()
                .eq(XcUser::getCellphone, request.getCellphone()));
        if(phoneExist > 0){
            throw new RuntimeException("当前手机号已存在");
        }
        int emailExist = count(new LambdaQueryWrapper<XcUser>()
                .eq(XcUser::getEmail, request.getEmail()));
        if(emailExist > 0){
            throw new RuntimeException("当前邮箱已存在");
        }
        //然后添加新用户
        XcUser user = new XcUser();
        BeanUtils.copyProperties(request,user);
        user.setStatus("1");
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        save(user);
        //添加完用户之后，还要添加对应的角色关系
        XcUserRole userRole = new XcUserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(17L);    //注册的就是学生用户
        return user;
    }
}
